#include "noticemanagerapi.h"

NoticeManagerApi::NoticeManagerApi(QObject *parent)
    : QObject{parent}
{
    baseUrl = Config::baseUrl;
    manager = new QNetworkAccessManager(0);
    request.setHeader(QNetworkRequest::ContentTypeHeader,QVariant("application/json"));//post请求设置为json，才能发送josn格式文件
    request.setRawHeader("Authorization",  qApp->property("token").value<QString>().toLocal8Bit());

}

QByteArray *NoticeManagerApi::list(int pageNum, int pageSize,QString noticeTitle,QString operateUser,QString noticeType)
{
    QString params = "system/notice/list?pageNum="+ QString::number(pageNum) +
                     "&pageSize=" + QString::number(pageSize);
    if(!noticeTitle.isEmpty()){
        params += "&noticeTitle=" + noticeTitle;
    }
    if(!operateUser.isEmpty()){
        params += "&createBy=" + operateUser;
    }
    if(!noticeType.isEmpty()){
        params += "&noticeType=" + noticeType;
    }
    request.setUrl(baseUrl + params);
    QNetworkReply *reply= manager->get(request);
    //同步请求
    QEventLoop eventLoop;
    connect(reply, &QNetworkReply::finished, &eventLoop, &QEventLoop::quit);
    eventLoop.exec();
    data = new QByteArray(reply->readAll().data());
    reply->deleteLater();
    utils.requestCheck(data);
    return data;
}

QByteArray *NoticeManagerApi::editNotice(qlonglong noticeId, Notice &notice)
{
    request.setUrl(baseUrl + "system/notice");
    QJsonObject obj = notice.toJson();
    QByteArray arr = QJsonDocument(obj).toJson();
    QNetworkReply *reply = noticeId > 0 ? manager->put(request,arr) : manager->post(request,arr);
    //同步请求
    QEventLoop eventLoop;
    connect(reply, &QNetworkReply::finished, &eventLoop, &QEventLoop::quit);
    eventLoop.exec();
    data = new QByteArray(reply->readAll().data());
    reply->deleteLater();
    utils.requestCheck(data);
    return data;
}

QByteArray *NoticeManagerApi::getById(int noticeId)
{
    request.setUrl(baseUrl + "system/notice/" + QString::number(noticeId));
    QNetworkReply *reply = manager->get(request);
    //同步请求
    QEventLoop eventLoop;
    connect(reply, &QNetworkReply::finished, &eventLoop, &QEventLoop::quit);
    eventLoop.exec();
    data = new QByteArray(reply->readAll().data());
    reply->deleteLater();
    utils.requestCheck(data);
    return data;
}

QByteArray *NoticeManagerApi::deleteItems(QString ids)
{
    request.setUrl(baseUrl + "system/notice/" + ids);
    QNetworkReply * r = manager->deleteResource(request);
    //同步请求
    QEventLoop eventLoop;
    connect(r, &QNetworkReply::finished, &eventLoop, &QEventLoop::quit);
    eventLoop.exec();
    data = new QByteArray(r->readAll().data());
    r->deleteLater();
    utils.requestCheck(data);
    return data;
}
